<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow>
        <template #header>
          <el-breadcrumb separator-class="el-icon-arrow-right" v-if="$route.query.id? true: false"  >
          <el-breadcrumb-item>学科管理</el-breadcrumb-item>
          <el-breadcrumb-item>{{$route.query.name}}</el-breadcrumb-item>
          <el-breadcrumb-item>标签管理</el-breadcrumb-item>
        </el-breadcrumb>
        </template>
        <el-row>
          <el-col :span="19">
            <el-form :inline="true" :model="searchList">
              <el-form-item label="标签名称">
                <el-input
                  size="small"
                  v-model="searchList.tagName"
                >
                </el-input>
              </el-form-item>
              <el-form-item label="状态" style="margin-left: 50px">
                <el-select
                  size="small"
                  value-key="state"
                  v-model="searchList.state"
                >
                  <el-option label="启用" :value="1"></el-option>
                  <el-option label="禁用" :value="0"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="dafault" size="small" @click="clearSearch"
                  >清除</el-button
                >
                <el-button type="primary" size="small" @click="handleSearch"
                  >搜索</el-button
                >
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="5" class="flexEnd">
            <el-button type="text" icon="el-icon-back" v-show="$route.query.id? true: false" @click="$router.back()">返回学科
            </el-button>
            <el-button
              type="success"
              icon="el-icon-edit"
              size="small"
              @click="AddTag"
              >新增标签</el-button
            >
          </el-col>
        </el-row>
        <!-- 提示信息 -->
        <el-alert
          type="info"
          :closable="false"
          show-icon
          style="margin-bottom: 18px"
        >
        <template #title><span>数据一共{{total}}条</span></template>
        </el-alert>
        <!-- 数据表格 -->
        <el-table
          :data="tagsList"
          style="width: 100%"
          :header-cell-style="{
            'border-bottom': '2px solid rgb(232,232,232)',
            background: 'rgb(250,250,250)',
          }"
        >
          <el-table-column type="index" label="序号">
          </el-table-column>
          <el-table-column prop="subjectName" label="所属学科">
          </el-table-column>
          <el-table-column prop="tagName" label="标签名称"> </el-table-column>
          <el-table-column prop="username" label="创建者"> </el-table-column>
          <el-table-column prop="addDate" label="创建日期">
            <template #default="{ row }">
              {{ dayjs(row.addDate).format("YYYY-MM-DD HH:mm:ss") }}
            </template>
          </el-table-column>
          <el-table-column prop="state" label="状态" :formatter="formatterFn">
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button type="text" @click="handleDisabled(row)">{{
                row.state === 1 ? "禁用" : "启用"
              }}</el-button>
              <el-button
                type="text"
                @click="handleEdit(row)"
                :disabled="row.state===1?true:false"
                >修改</el-button
              >
              <el-button
                type="text"
                @click="handleDel(row)"
                :disabled="row.state===1?true:false"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-row type="flex" justify="end" v-if="total>5">
          <el-col :span="12">
            <el-pagination
              background
              style="margin-top: 20px"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page"
              :page-sizes="pagesizes"
              :page-size="pagesize"
              layout="prev, pager, next, sizes, jumper"
              :total="total"
            >
            </el-pagination>
          </el-col>
        </el-row>
        <!-- 新增/修改对话框 -->
        <el-dialog
          :title="dialogTitle"
          :visible="showDialog"
          width="30%"
          @close="CloseDialog"
        >
          <el-form
            :model="dialogForm"
            label-width="20%"
            :rules="dialogRules"
            ref="DialogRef"
          >
            <el-form-item size="small" label="所属学科" prop="subjectID" v-show="$route.query.id? false : true" required>
              <el-select
                placeholder="请选择"
                style="width: 100%"
                v-model="dialogForm.subjectID"

              >
                <el-option
                  v-for="item in subList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item size="small" label="目录名称" prop="tagName">
              <el-input
                placeholder="请输入目录名称"
                v-model="dialogForm.tagName"
              ></el-input>
            </el-form-item>
          </el-form>
          <template #footer class="dialog-footer">
            <el-button type="default" @click="CloseDialog">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确认</el-button>
          </template>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { list, remove, update, add, changeState } from '@/api/hmmm/tags'
import { simple } from '@/api/hmmm/subjects'
import dayjs from 'dayjs'
export default {
  data () {
    const checkSubID = (rule, value, cb) => {
      if (this.$route.query.id) {
        // this.dialogForm.subjectID = +this.$route.query.id
        return cb()
      }
      if (!value) {
        return cb(new Error('请选择所属学科'))
      } else {
        cb()
      }
    }
    return {
      // 主体标签列表(table)
      tagsList: [],
      subList: [],
      // 顶部搜索内容(form)
      searchList: {
        tagName: '', // 要搜索的标签名称
        state: null // 要搜索的状态展示框
      },
      chaoZhao: {},
      showDialog: false,
      // 弹出框表单内容(form)
      dialogForm: {
        subjectID: '',
        tagName: ''
      },
      total: 0, // 总条数
      page: 1, // 当前页码
      pagesize: 10, // 当前页数据条数
      pagesizes: [5, 10, 15, 20], // 可选的当前页的条数
      // dialog表单规则
      dialogRules: {
        subjectID: [
          { validator: checkSubID, trigger: ['blur', 'change'] }
        ],
        tagName: [
          {
            required: true,
            message: '请输入目录名称',
            trigger: ['change', 'blur']
          }
        ]
      },
      dayjs, // 上面用插值处理，此处就必须引入
      dialogTitle: ''
    }
  },
  async created () {
    // 一上来就发请求获取标签列表(如果是从学科管理进来(带id发list请求)，否则直接页面渲染)
    // console.log(this.$route.query.id)
    if (this.$route.query.id) {
      const { data } = await list({ subjectID: this.$route.query.id })
      // console.log('11', data)
      this.tagsList = data.items
      this.total = data.counts
      // this.dialogForm.subjectID = +this.$route.query.id
    } else {
      this.getTagsList()
    }
    if (this.$route.query.id) {
      this.dialogForm.subjectID = +this.$route.query.id
    }
  },
  methods: {
    // 获取标签列表（状态和时间需要二次处理）
    async getTagsList () {
      const { data: data1 } = await simple()
      const { data: res } = await list({ subjectID: +this.$route.query.id || null, page: this.page, pagesize: this.pagesize })
      // console.log('标签列表', data1)
      this.tagsList = res.items
      this.total = res.counts
      this.subList = data1
    },
    // 列表状态（0/1）格式化处理
    formatterFn (row, column, cellValue, index) {
      // console.log(row, column, cellValue, index)
      return cellValue === 1 ? '已启用' : '已禁用'
    },
    // 切换页
    async handleCurrentChange (val) {
      // 携带当前页码发请求list请求，将结果赋值给tagsList
      this.page = val
      this.getTagsList()
    },
    // 切换每页条数
    handleSizeChange (val) {
      // 拿到每页条数去发list请求，将结果赋值给tagsList
      this.pagesize = val
      this.page = 1
      this.getTagsList()
    },
    // 清除搜索内容
    clearSearch () {
      // 清空searchTagName和searchState
      this.searchList = {
        tagName: '', // 要搜索的标签名称
        state: '' // 要搜索的状态展示框
      }
    },
    // 搜索功能
    async handleSearch () {
      const { data } = await list({
        subjectID: +this.$route.query.id || null,
        tagName: this.searchList.tagName,
        state: this.searchList.state,
        page: 1,
        pagesize: 10
      })
      this.tagsList = data.items
      this.total = data.counts || 0
    },
    // 新增标签
    AddTag () {
      // 展示dialog且对表单DialogRef进行预校验，校验通过发请求，然后请求最新的tagsList
      this.dialogTitle = '新增目录'
      this.showDialog = true
    },
    // 启用禁用按钮功能
    async handleDisabled (row) {
      // 将数据对应的状态取反，修改和删除的样式改为disabled，操作按钮显示也取反
      row.state === 0 ? row.state = 1 : row.state = 0
      await changeState(row)
      if (this.$route.query.id) {
        const { data } = await list({ subjectID: this.$route.query.id })
        // console.log('11', data)
        this.tagsList = data.items
        this.total = data.counts
      } else {
        this.getTagsList()
      }
      this.$message.success('操作成功')
    },
    // 关闭对话框
    CloseDialog () {
      // 隐藏当前dialog框且将表单内容和校验都清空
      this.showDialog = false
      this.$refs.DialogRef.resetFields()

      this.dialogForm = {
        subjectID: +this.$route.query.id || '',
        tagName: ''
      }
    },
    // 确认对话框
    handleSubmit () {
      // 判断是对话框功能添加还是修改(有无id)
      // 如果是添加通过预校验再发add请求，如果是修改进行比对之前和现在的数据，不一致就发update请求，否则不发
      this.$refs.DialogRef.validate(async (valid) => {
        if (valid) {
          // 如果是从别家进来
          if (this.$route.query.id) {
            // 如果是修改
            if (this.dialogForm.id) {
              await update(this.dialogForm)
              const { data } = await list({
                subjectID: this.$route.query.id
              })
              this.tagsList = data.items
              this.total = data.counts
            } else {
              // 如果是添加
              await add(this.dialogForm)
              const { data } = await list({
                subjectID: this.$route.query.id
              })
              this.tagsList = data.items
              this.total = data.counts
            }
          } else {
            // 如果是自己家进来
            // 修改
            if (this.dialogForm.id) {
              await update(this.dialogForm)
              this.getTagsList()
            } else {
              // 增加
              // console.log('增加')
              await add(this.dialogForm)
              this.getTagsList()
            }
          }
        } else {
          console.log('error submit!!')
          return false
        }
        this.CloseDialog()
        this.$message.success('操作成功')
      })
    },
    // 显示修改弹框
    async handleEdit (row) {
      this.dialogTitle = '修改目录'
      // 展示dialog且将title改为修改状态，拿到当前数据并回显
      this.showDialog = true
      this.dialogForm = { ...row }
    },
    // 删除功能
    handleDel (row) {
      // 弹出确认框且询问取消还是确定，取消不发请求，确定则带id发remove请求，且获取最新的tagsList
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(async () => {
          await remove(row)
          this.getTagsList()
          this.$message.success('删除成功')
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__footer {
  text-align: right !important;
}

.flexEnd {
  display: flex;
  justify-content: flex-end;
}
.el-pagination {
   display: flex;
  justify-content: flex-end;
}
</style>
